//
//  NetWorkTool.swift
//  SwiftProject
//
//  Created by qindong on 2022/7/27.
//

import Moya
import HandyJSON

/// 设置超时时间
let timeoutInterval : TimeInterval = 60

/// 自定义的moya -》Providerp
let provider = MoyaProvider<MyService>(endpointClosure: myEndpointClosure, plugins:[RequestLoadingPlugin(), DeBugPlugin(), AuthPlugin()])
let downloadProvider = MoyaProvider<MyService>(endpointClosure: myEndpointClosure, plugins:[RequestLoadingPlugin(), AuthPlugin()])

/// 接口枚举
enum MyService {
    case authAppLogin(phoneAes : String, captcha : String)
    
    case register(mobile:String, pwd:String)
    
    case initApp
    
    case authCaptcha(phoneAes : String)
    
    case idcardAudit(name : String, idCard : String)
    
    case genRealPersonVerificationToken(name : String, idCard : String, metaInfo : String)
    
    case getRealPersonVerificationResult(name : String, idCard : String)
    
    case recognizeIdcard(url : String)
    
    case ipPositioning
    
    case city
    
    case productInfo
    
    case productInfoUrl(productId : Int)
    
    case routeProductInfo
    
    case accountMember(model : FQFillResultModel)
    
    case initUserInfo
    
    case cancelUser
    /// 方便获取baseurl
    case getBase
}

extension MyService : TargetType {
    var baseURL : URL {
        switch self {
        default:
            #if kTargetProduct
            return URL(string: "http://app.jiyongfq.com")!
            #elseif kTargetDevelop
            return URL(string: "http://app.jiyongfq.com")!
            #endif
        }
    }
    
    var validationType : ValidationType {
        return .none
    }
    
    var path : String {
        switch self {
        case .authAppLogin:
            return "/prod-api/auth/appLogin"
        case .initApp:
            return "/prod-api/app/app/init"
        case .authCaptcha:
            return "/prod-api/auth/captcha"
        case .idcardAudit:
            return "/prod-api/app/ocr/idcardAudit"
        case .genRealPersonVerificationToken:
            return "/prod-api/app/faceverify/genRealPersonVerificationToken"
        case .getRealPersonVerificationResult:
            return "/prod-api/app/faceverify/getRealPersonVerificationResult"
        case .recognizeIdcard:
            return "/prod-api/app/ocr/recognizeIdcard"
        case .ipPositioning:
            return "/prod-api/app/app/ipPositioning"
        case .city:
            return "/prod-api/app/app/citys"
        case .accountMember:
            return "/prod-api/app/app/AppAccountMember"
        case .productInfo:
            return "/prod-api/app/app/productinfo"
        case .initUserInfo:
            return "/prod-api/app/app/initUserInfo"
        case .productInfoUrl:
            return "/prod-api/app/app/productinfo/url"
        case .routeProductInfo:
            return "/prod-api/app/app/route/productinfo"
        case .cancelUser:
            return "/prod-api/app/app/cancelUser"
        default:
            return ""
        }
    }
    
    var method : Moya.Method {
        switch self {
        case .initApp, .authCaptcha, .authAppLogin, .idcardAudit, .genRealPersonVerificationToken, .getRealPersonVerificationResult, .recognizeIdcard, .ipPositioning, .city, .accountMember, .productInfo, .initUserInfo, .productInfoUrl, .routeProductInfo, .cancelUser:
            return .post
        default:
            return .get
        }
    }
    
    // 请求任务事件（这里附带上参数）
    var task : Task {
        var parmeters: [String : Any] = ["appId" : 101, "channel" : 1000, "osType" : "2", "osName" : DeviceManager.modelName, "clientUa" : "clientUa"]
        if let model = BaseUserModel.unarchiver() {
            parmeters["channelToken"] = model.channelToken
        }
        switch self {
        case .authCaptcha(let phoneAes):
            parmeters["phoneAes"] = phoneAes
            parmeters["osId"] = "ios"
            parmeters["channelToken"] = "123"
            parmeters["channelNumber"] = "1000"
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .authAppLogin(let phoneAes, let captcha):
            parmeters["phoneAes"] = phoneAes
            parmeters["osId"] = "ios"
            parmeters["captcha"] = captcha
            parmeters["channelToken"] = "1"
            parmeters["channelNumber"] = "1000"
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .idcardAudit(let name, let idCard):
            parmeters["name"] = name
            parmeters["idCard"] = idCard
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .genRealPersonVerificationToken(let name, let idCard, let metaInfo):
            parmeters["name"] = name
            parmeters["idCard"] = idCard
            parmeters["metaInfo"] = metaInfo
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .getRealPersonVerificationResult(let name, let idCard):
            parmeters["name"] = name
            parmeters["idCard"] = idCard
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .recognizeIdcard(let url):
            parmeters["url"] = url
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .ipPositioning, .city:
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .accountMember(let model):
            let dict = model.toJSON()
            parmeters.merge(dict: dict!)
            parmeters["phoneAes"] = WMEncryptTool.manager.aesEncrypt(BaseUserModel.unarchiver()!.phone)
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .productInfo:
            parmeters["phoneAes"] = WMEncryptTool.manager.aesEncrypt(BaseUserModel.unarchiver()!.phone)
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .initUserInfo:
            parmeters["phoneAes"] = WMEncryptTool.manager.aesEncrypt(BaseUserModel.unarchiver()!.phone)
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .productInfoUrl(let productId):
            parmeters["phoneAes"] = WMEncryptTool.manager.aesEncrypt(BaseUserModel.unarchiver()!.phone)
            parmeters["productId"] = productId
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .routeProductInfo:
            parmeters["phoneAes"] = WMEncryptTool.manager.aesEncrypt(BaseUserModel.unarchiver()!.phone)
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        case .cancelUser:
            parmeters["phoneAes"] = WMEncryptTool.manager.aesEncrypt(BaseUserModel.unarchiver()!.phone)
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        default:
            return .requestParameters(parameters: parmeters, encoding: JSONEncoding.default)
        }
    }
    
    //这个就是做单元测试模拟的数据，
    //只会在单元测试文件中有作用
    var sampleData : Data {
        return "{}".data(using: .utf8)!
    }
    
    //如果请求头不一致还需要单独设置请求头
    var headers: [String : String]? {
        switch self {
        default:
            let intstamp = Date().timeIntervalSince1970 * 1000
            let timestamp : String = String(format: "%.0f", intstamp)
            let encryptString : String = WMEncryptTool.manager.des_encrypt_c(timestamp: timestamp)
            var dict = ["Content-type": "application/json", "timestamp" : timestamp, "ciphertext" : encryptString]
            if let model = BaseUserModel.unarchiver() {
                dict["Authorization"] = "Bearer " + model.access_token
            }
            return dict
        }
    }
    
    var cachePolicy: URLRequest.CachePolicy {
        switch self {
        default:
            return .useProtocolCachePolicy
        }
    }
    
    //是否需要授权
    var needsAuth: Bool {
        switch self {
        default:
            return false
        }
    }
}

/// 可以对请求头进行一些全局操作
let myEndpointClosure = { (target: MyService) -> Endpoint in
    var baseUrl = target.baseURL
    if baseUrl.path.count > 0 && !baseUrl.absoluteString.hasPrefix("/") {
        baseUrl = baseUrl.appendingPathComponent("")
    }
    // 自动拼接url
    let url = URL(string: target.path, relativeTo: baseUrl)!
    let endpoint = Endpoint(
        url: url.absoluteString,
        sampleResponseClosure: { .networkResponse(200, target.sampleData) },
        method: target.method,
        task: target.task,
        httpHeaderFields: target.headers
    )
    //在这里设置通用的HTTP头部信息
    return endpoint.adding(newHTTPHeaderFields: [
        "model": "iPhone",
        "os-name": "iOS",
        "os-version": "14.5",
        "appVersion": "2.7.6",
        "clientType": "2",
        "kwidth": "390.000000",
        "kheight": "844.000000",
        "app_location": "222 222 222",
        "source": "100"
    ])
}

/// 默认下载保存地址（用户文档目录可自定义）
let DefaultDownloadDir : URL = {
    let directoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return directoryURLs.first ?? URL(fileURLWithPath: NSTemporaryDirectory())
}()

/// 定制请求设置类
class RequestLoadingPlugin : PluginType {
    func prepare(_ request: URLRequest, target: TargetType) -> URLRequest {
        // print("prepare")
        var mRequest = request
        // 请求超时限制
        mRequest.timeoutInterval = timeoutInterval
//        if let cachePolicyGettable = target as? MyService {
//            mRequest.cachePolicy = cachePolicyGettable.cachePolicy
//        }
        return mRequest
    }
    
    func willSend(_ request: RequestType, target: TargetType) {
        //print("开始请求")
    }
    
    func didReceive(_ result: Result<Response, MoyaError>, target: TargetType) {
        //print("结束请求")
//        guard case let Result.failure(faildResponse) = result else {
//            let response = try! result.get()
//            let data = response.data
//            guard let jsonDic = try? JSONSerialization.jsonObject(with: data) as? [String : Any] else {
//                return
//            }
            // 这里可以统一做错误处理
//            switch jsonDic["code"] as! Int {
//            default:
//                print(jsonDic["msg"] ?? "")
//            }
//            return
//        }
    }
}


    
